-- 雪花算法

CREATE SEQUENCE IF NOT EXISTS snow_count_seq increment by 1 maxvalue 99999999 minvalue 1 start 1 cycle;
 
create or replace function snow_next_id (WorkerID int) returns bigint as $$
DECLARE
   init_epoch bigint:=1577836800000;
   seq_id bigint;
   now_millis bigint;
   result bigint;
BEGIN
   seq_id:=nextval('snow_count_seq') % 16384;
   SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
   result:=(now_millis - init_epoch) << 20;
   result:=result | (WorkerID << 14);
   result:=result | (seq_id);
   
   return result;
END;
$$ LANGUAGE PLPGSQL;